package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.LoginDto;
import com.zzyl.entity.User;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.LoginService;
import com.zzyl.service.ResourceService;
import com.zzyl.service.UserService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Max;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProp;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public UserVo login(LoginDto dto) {
        //判断用户名是否存在
        User user = userService.findUserByUserName(dto.getUsername());
        if (user == null){
            log.error("用户名不存在！");
            throw new BaseException(BasicEnum.USER_EMPTY_EXCEPTION);
        }
        //判断是否被禁用
        if ("1".equals(user.getDataState())){
            log.error("用户已被禁用");
            throw new BaseException(BasicEnum.USER_EMPTY_EXCEPTION);
        }
        //判断密码是否正确
        //使用Bcrypt对比
        boolean b = BCrypt.checkpw(dto.getPassword(), user.getPassword());
        if (!b){
            log.error("密码错误");
            throw new BaseException(BasicEnum.ORIGINAL_PASSWORD_ERROR);
        }
        //密码脱敏
        UserVo vo = BeanUtil.toBean(user, UserVo.class);
        vo.setPassword("");
        //生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("currentUser", JSONUtil.toJsonStr(vo));
        String token = JwtUtil.createJWT(jwtTokenManagerProp.getBase64EncodedSecretKey(),
                jwtTokenManagerProp.getTtl(), claims);
        vo.setUserToken(token);
        //将用户可以访问按钮的路径保存到redis
        //获取userId
        Long userId = user.getId();
        //获取用户可以访问按钮的路径
        List<String> urls = resourceService.findButListByUserId(userId);
        //保存到redis
        redisTemplate.opsForValue().set("user:access:urls:" + userId, JSONUtil.toJsonStr(urls));
        //返回
        return vo;
    }
}
